package com.myc.train.generator.server;


import com.myc.train.generator.util.DbUtil;
import com.myc.train.generator.util.Field;
import com.myc.train.generator.util.FreemarkerUtil;
import freemarker.template.TemplateException;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Node;
import org.dom4j.io.SAXReader;

import java.io.File;
import java.io.IOException;
import java.util.*;

public class ServerGenerator {

//    static String toPath = "generator\\src\\main\\java\\com\\myc\\train\\generator\\test\\";

    static boolean readOnly = true;

    static String vuePath = "admin/src/views/main/";
    static String servicePath = "train-[module]/src/main/java/com/myc/train/[module]/";
    static String pomPath = "generator\\pom.xml";

    static {
        new File(servicePath).mkdirs();
    }

    public static void main(String[] args) throws Exception {

        //获取myvatis-generator
        String generatorPath = getGeneratorPath();
        //获取当前用的什么数据库的xml文件并截取出实体名字
       String module = generatorPath.replace("src/main/resources/generator-config-","").replace(".xml","");
        System.out.println("module: " + module);
        //替换servicePath中的路径
        servicePath =  servicePath.replace("[module]" , module);
        System.out.println("servicePath: " + servicePath);

        //读取table节点
        Document document = new SAXReader().read("generator/" + generatorPath);
        Node table = document.selectSingleNode("//table");
        System.out.println(table);
        Node tableName = table.selectSingleNode("@tableName");
        Node domainObjectName = table.selectSingleNode("@domainObjectName");
        System.out.println(tableName.getText() + "/" +domainObjectName.getText());

        //读取数据库表DBUtil节点
        Node connectionURL = document.selectSingleNode("//@connectionURL");
        Node userId = document.selectSingleNode("//@userId");
        Node password = document.selectSingleNode("//@password");
        System.out.println("URL的值是："+connectionURL.getText());
        System.out.println("userId："+userId.getText());
        System.out.println("passwd："+password.getText());

        DbUtil.url = connectionURL.getText();
        DbUtil.user = userId.getText();
        DbUtil.password = password.getText();

        //改表名
        //1.Domain = MycTest
        String Domain = domainObjectName.getText();
        //2.domain = mycTest
        String domain = Domain.substring(0,1).toLowerCase() + Domain.substring(1);
        //3.do_main = myc-test
        String do_main = tableName.getText().replaceAll("_","-");

        //传表中文名
        String tableNameCn = DbUtil.getTableComment(tableName.getText());
        List<Field> fieldList = DbUtil.getColumnByTableName(tableName.getText());
        Set<String> typeSet = getJavaTypes(fieldList);

        //组装参数
        Map<String, Object> map = new HashMap<>();
        map.put("Domain",Domain);
        map.put("module",module);
        map.put("domain",domain);
        map.put("do_main",do_main);
        map.put("tableNameCn", tableNameCn);
        map.put("fieldList", fieldList);
        map.put("typeSet", typeSet);
        map.put("readOnly", readOnly);
        System.out.println("组装参数："+map);

        genService(Domain, map , "service" , "service");
        genService(Domain, map , "controller/admin" , "adminController");
        genService(Domain,map,"req","saveReq");
        genService(Domain, map, "req", "queryReq");
        genService(Domain, map, "resp", "queryResp");
        genVue(do_main, map);
    }

    private static void genService(String Domain, Map<String, Object> map , String packageName,String target) throws IOException, TemplateException {
        FreemarkerUtil.initConfig(target + ".ftl");
        String toPath = servicePath + packageName + "/";
        new File(toPath).mkdirs();
        String Target = target.substring(0,1).toUpperCase() + target.substring(1);
        String fileName = toPath +Domain +Target + ".java";
        System.out.println("开始生成：" + fileName);
        FreemarkerUtil.generator(fileName, map);
    }

    private static void genVue(String do_main, Map<String, Object> param) throws IOException, TemplateException {
        FreemarkerUtil.initConfig("vue.ftl");
        new File(vuePath).mkdirs();
        String fileName = vuePath + do_main + ".vue";
        System.out.println("开始生成：" + fileName);
        FreemarkerUtil.generator(fileName, param);
    }

    private static String getGeneratorPath() throws DocumentException {
        SAXReader saxReader = new SAXReader();
        Map<String,String> map = new HashMap<String,String>();
        map.put("pom","http://maven.apache.org/POM/4.0.0");
        saxReader.getDocumentFactory().setXPathNamespaceURIs(map);
        Document read = saxReader.read(pomPath);
        Node node = read.selectSingleNode("//pom:configurationFile");
        System.out.println(node.getText());
        return node.getText();
    }

    /**
     * 获取所有的Java类型，使用Set去重
     */
    private static Set<String> getJavaTypes(List<Field> fieldList) {
        Set<String> set = new HashSet<>();
        for (int i = 0; i < fieldList.size(); i++) {
            Field field = fieldList.get(i);
            set.add(field.getJavaType());
        }
        return set;
    }

}
